有鑑於我之前的寫法是屬於 Options 的方式,今天在看 doc 的時候發現了有 Composition 的寫法,所以想要來練習看看
Options API
<template>
<div class="box">
<button @click="inc">{{ count }}</button>
</div>
</template>
<script>
export default {
data() {
return { count: 0 }
},
methods: {
inc(){
this.count++
}
}
}
</script>
Composition API
<script setup>
import { ref } from 'vue'
const count = ref(0)
const inc = () => count.value++
</script>
comparison
項目 | Options API | Composition API / <script setup> |
---|---|---|
版本 | Vue 2 起(Vue 3 仍支援) | Vue 3 引入;<script setup> 自 3.2 |
寫法 | 依區塊分:data/methods/computed |
相關邏輯放一起:setup() / <script setup> |
上手度 | 相對好懂、適合入門 | 一開始稍難,但更彈性 |
當我們在修改了響應式的 instance
時,DOM 會自動更新。我們的 DOM 更新並不是同步的。 Vue 會把「這次的修改」先記下來,等「本次 JavaScript 執行結束」後,再一次更新完,避免多次的狀態更新造成重複渲染
eg.
<script setup>
import { ref, nextTick } from 'vue'
const count = ref(0)
const textclass = ref('tick_test')
async function incrementTwice() {
count.value++
count.value++
console.log("Tick 前:", document.querySelector("p").innerText)
await nextTick()
console.log("Tick 後:", document.querySelector("p").innerText)
}
</script>
<template>
<div class="box">
<p :class="textclass">{{ count }}</p>
<button @click="incrementTwice">+2</button>
</div>
</template>
<style scoped>
.box{
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
text-align: center;
border: solid;
margin-left: 850px;
height: 120px;
width:250px;
}
</style>
可以看到同一個標籤在 tick
前後的值不一樣,Vue 在一次批次更新後統一處理,提高效能
ref:
https://zh-hk.vuejs.org/guide/essentials/reactivity-fundamentals.html#ref
https://book.vue.tw/CH6/6-1-composition-intro.html